import './index.less';
import useTreeData from './hooks/useTreeNodes';
import CustomIcon from '../Icon/CustomIcon';
import { TreeNode } from '@/domain/tree';

export interface TreeProps {
    className?: string,
    nodes: Array<TreeNode>,
    selectKey: string,
    clickNode: (e: React.MouseEvent, node: TreeNode) => void,
}

function Tree({ className = '', nodes, clickNode, selectKey = ''}: TreeProps) {
    const { treeNodes, setTreeNodes, updateTree } = useTreeData(nodes, selectKey);
    const onClickTreeNode = (e: React.MouseEvent, node: TreeNode) => {
        e.stopPropagation();
        if (!node.children) {
            console.log('the clicked node is ', node.label);
            clickNode && clickNode(e, node);
            return;
        }
        setTreeNodes(updateTree(treeNodes, node.key));
    }
    function render(nodes: Array<TreeNode>, level: number) {
        if (!nodes) {
            return '';
        }
        return nodes.map((node: TreeNode) => {
            return (
                <div className={`tree-node`} key={node.key}>
                    <div className={`node-content iconfont-box child-${level} ${selectKey === node.key ? 'select' : ''}`} onClick={(e) => onClickTreeNode(e, node)}>
                        {node.icon ? <CustomIcon icon={node.icon}></CustomIcon> : ''}
                        <span className="flex-1">{node.label}</span>
                        {node.children && node.children.length > 0 ? <span className={`arrow ${node.isExpand ? 'down' : 'right'}`}></span> : ''}
                    </div>
                    {node.isExpand && node.children ? <div className={`node-children`}>{render(node.children, level + 1)}</div> : ''}
                </div>
            );
        });
    }
    return <div className={`${className} tree`}>{render(treeNodes, 0)}</div>;
}

export default Tree;
